package cn.com.huak.www.sell.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信网页授权
 *  通过sdk的方式
 * @author huak@wanggang
 * @date 2019/1/6 20:28
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @RequestMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        String url = "http://forever.natapp1.cc/sell/wechat/userinfo";
        String result = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnUrl);
        log.info("【微信网页授权】返回信息:{}", result);
        return "redirect:" + result;
    }


    @RequestMapping("/userinfo")
    public String userinfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnUrl){
        try {
            log.info("【微信网页授权】code:{}, returnUrl：{}", code, returnUrl);
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            log.info("access_token:{}", wxMpOAuth2AccessToken.getAccessToken());
            log.info("openid:{}", wxMpOAuth2AccessToken.getOpenId());
            return "redirect:" + returnUrl + "?openid=" + wxMpOAuth2AccessToken.getOpenId();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "";
    }
}
